<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax Card</title>
</head>
<body>
<ul id="deck"></ul>
<form>
    <input name="name" type="text"/>
    <input value="提交" type="submit"/>
</form>
<!-- 要加载额外的JS文件，得使用中间件配合 -->
<script type="application/javascript" src="/scripts/jquery-1.8.3.min.js"></script>
<script type="application/javascript">

    function appendCard (data) {
        var list = [];
        for (var i = 0; i < data.length; i++) {
            var content = data[i].name + "&nbsp;<a href='javascript:void(0)' data-cardname='"+data[i].name+"'>删除</a>";
            list.push($('<li>',{html: content}));
        }
        $('#deck').append(list);
    }

    $(document).ready(function () {
        $.ajax({
            type: 'GET',
            url: '/deck',
            success: appendCard
        });
    });

    $('form').on('submit', function (event) {
        event.preventDefault();
        var _form = $(this);
        $.ajax({
            type: 'POST',
            url: '/card_add',
            data: _form.serialize()
        }).done(function (data) {
            appendCard([data]);
            _form.trigger('reset');
            console.info(this);
        });
    });

    $('#deck').on('click','a[data-cardname]', function (event) {
        var cardname = $(this).data('cardname');
        var target = $(event.currentTarget);
        $.ajax({
            type: 'DELETE',
            url: '/card_delete/'+cardname,
        }).done(function (data) {
            if('OK' === data) {
                target.parents('li').remove();
            }
        });
    });
</script>
</body>
</html>